package com.qd.system.service.dict;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.dict.DictDataDTO;
import com.qd.system.mapper.DictDataMapper;
import com.qd.system.model.DictData;
import com.qd.system.model.DictType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DictDataService extends BaseService<DictDataMapper, DictData> {

    public static final String PREFIX_LIST = "sys_dict_data_type_id_{0}";
    /**
     * 状态，启用、停用
     */
    public static final String STATUS = "dm_base_status";
    public static final String TYPE_ID = "type_id";
    private static final String PREFIX_ID = "sys_dict_data_id_{0}";
    private static final String PREFIX_TYPE_ID = "sys_dict_data_type_{0}";
    private static final Integer MAX_CURRENT = 9999;
    private final RedisTemplateUtil<DictData> redisTemplateUtil;
    private final HttpServletResponse response;
    private final DictTypeService dictTypeService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public DictDataDTO save(DictDataDTO dto) {
        checkMb(dto);
        final DictData model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public DictDataDTO update(DictDataDTO dto) {
        checkMb(dto);
        final DictData historyModel = Optional.ofNullable(getById(dto.getId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final DictData model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<DictData> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<DictData> mList) {
        final List<String> ids = mList.stream().map(DictData::getId).collect(toList());
        final List<DictData> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param id 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        final DictData model = getById(id);
        if (null == model) {
            throw new ApiException("数据不存在,不能删除");
        }
        try {
            if (!super.removeById(id)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<DictData> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(DictDataDTO dto) {
        final QueryWrapper<DictData> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param id 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String id) {
        boolean exists = false;
        if (StringUtils.hasLength(id)) {
            final DictData model = getById(id);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public DictData getById(String id) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(id), DictData.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public DictDataDTO getByIdDto(String id) {
        final DictData model = getById(id);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public DictData getOne(DictDataDTO dto) {
        final QueryWrapper<DictData> queryWrapper = createQueryWrapper(dto);
        final DictData model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public DictDataDTO getOneDto(DictDataDTO dto) {
        final DictData model = getOne(dto);
        if (null == model) {
            return null;
        }
        final DictDataDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<DictData> getList(DictDataDTO dto) {
        final QueryWrapper<DictData> queryWrapper = createQueryWrapper(dto);
        final List<DictData> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<DictDataDTO> getListDto(DictDataDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<DictDataDTO> page(Page<DictData> page, DictDataDTO dto) {
        final QueryWrapper<DictData> queryWrapper = createQueryWrapper(dto, "dic.");
        final IPage<DictDataDTO> iPage = getBaseMapper().page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     * @throws IOException 异常
     */
    @Transactional(readOnly = true)
    public void export(DictDataDTO query) throws IOException {
        final ExportPage<DictData, DictDataDTO> exportPage = new ExportPage<>();
        try {
            final List<DictDataDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, DictDataDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    @Transactional(readOnly = true)
    public void clearCache(DictData model) {
        String typeId = model.getTypeId();
        final String id = model.getId();
        if (!StringUtils.hasLength(typeId)) {
            final DictData dictData = getById(model.getId());
            if (dictData != null) {
                typeId = dictData.getTypeId();
                dictData.freeData();
            }
        }
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id);
        redisTemplateUtil.deleteByKey(key);
        if (StringUtils.hasLength(typeId)) {
            clearCacheByTypeId(typeId);
        }
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<DictData> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        list.forEach(this::clearCache);
    }

    /**
     * 按类型清除缓存
     *
     * @param typeId 类型ID
     */
    public void clearCacheByTypeId(String typeId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, typeId);
        redisTemplateUtil.deleteByKey(key);
        key = RedisTemplateUtil.getRedisCacheKey(PREFIX_TYPE_ID, typeId);
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 清除全部缓存
     */
    public void clearCacheAll() {
        final String pattern = "sys_dict_data_*";
        final Set<String> keys = redisTemplateUtil.getStringRedisTemplate().keys(pattern);
        assert keys != null;
        redisTemplateUtil.getStringRedisTemplate().delete(keys);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public DictDataDTO modelToDto(DictData model) {
        if (null == model) {
            return null;
        }
        final DictDataDTO dto = new DictDataDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setIdx(model.getIdx());
        dto.setStatus(model.getStatus());
        dto.setRemark(model.getRemark());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setTypeId(model.getTypeId());
        buildDisplay(dto);
        return dto;
    }

    private void buildDisplay(DictDataDTO dto) {
        dto.setStatusDisplay(MbUtil.idToDisplay(dto.getStatus()));
        dto.setTypeIdDisplay(dictTypeService.idToDisplay(dto.getTypeId()));
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public DictData dtoToModel(DictDataDTO dto) {
        if (null == dto) {
            return null;
        }
        final DictData model = new DictData();
        model.setId(dto.getId());
        model.setName(dto.getName());
        model.setIdx(dto.getIdx());
        model.setStatus(dto.getStatus());
        model.setRemark(dto.getRemark());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setTypeId(dto.getTypeId());
        return model;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<DictDataDTO> modelToDtoList(List<DictData> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<DictData> dtoToModelList(List<DictDataDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<DictData> createQueryWrapper(DictDataDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<DictData> createQueryWrapper(DictDataDTO dto, String tableAlias) {
        final QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getId())) {
                queryWrapper.like(tableAlias + "id", dto.getId());
            }
            if (StringUtils.hasLength(dto.getName())) {
                queryWrapper.like(tableAlias + "name", dto.getName());
            }
            if (null != dto.getStatus()) {
                queryWrapper.eq(tableAlias + "status", dto.getStatus());
            }
            if (StringUtils.hasLength(dto.getTypeId())) {
                queryWrapper.eq(tableAlias + TYPE_ID, dto.getTypeId());
            }
            if (StringUtils.hasLength(dto.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
            }
            if (StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
            }
        }
        queryWrapper.orderByAsc(tableAlias + TYPE_ID);
        queryWrapper.orderByAsc(tableAlias + "idx");
        return queryWrapper;
    }

    /**
     * 检查码表值是否正确
     *
     * @param DictDataDTO 前端参数
     */
    private void checkMb(DictDataDTO DictDataDTO) {
        if (null != DictDataDTO.getStatus()) {
            if (!MbUtil.isExists(DictDataDTO.getStatus())) {
                throw new ApiException("状态错误");
            }
        }
        if (StringUtils.hasLength(DictDataDTO.getTypeId())) {
            final DictType dictType = dictTypeService.getById(DictDataDTO.getTypeId());
            if (null == dictType) {
                throw new ApiException("字典类型错误");
            }
        }
    }

    /**
     * 递归存储数据到redis
     *
     * @param current     当前次数，最大9999
     * @param DictDataDTO 查询条件
     */
    @Transactional(readOnly = true)
    public void setRedisCache(int current, DictDataDTO DictDataDTO) {
        if (current > MAX_CURRENT) {
            return;
        }
        final Page<DictData> pageReq = new Page<>(current, 1000);
        final Page<DictDataDTO> dictDataPage = (Page<DictDataDTO>) page(pageReq, DictDataDTO);
        final List<DictDataDTO> records = dictDataPage.getRecords();
        if (!records.isEmpty()) {
            String key;
            for (DictDataDTO r : records) {
                key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, r.getId());
                redisTemplateUtil.set(new CacheKey().setKey(key), dtoToModel(r));
            }
        }
        if (dictDataPage.hasNext()) {
            setRedisCache(current + 1, DictDataDTO);
        }
    }

    @Transactional(readOnly = true)
    public List<DictDataDTO> getListByTypeDto(String typeId) {
        final List<DictData> list = getListByType(typeId);
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getListByTypes(List<String> types) {
        final Map<String, Object> map = new LinkedHashMap<>(types.size());
        types.forEach(type -> {
            if (STATUS.equals(type)) {
                final List<Map<String, Object>> list = MbUtil.getList();
                map.put(type, list);
            } else {
                final List<DictDataDTO> list = getListByTypeDto(type);
                map.put(type, list);
            }
        });
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByTypeId(String typeId) {
        final List<DictData> list = getListByType(typeId);
        if (!list.isEmpty()) {
            return;
        }
        clearCacheByTypeId(typeId);
        dictTypeService.removeById(typeId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByTypeIds(List<String> list) {
        List<DictData> typeList;
        for (String typeId : list) {
            typeList = getListByType(typeId);
            if (!typeList.isEmpty()) {
                return;
            }
        }
        dictTypeService.removeBatchIds(list);
    }

    @Transactional(readOnly = true)
    public List<DictData> getListByType(String typeId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(DictDataService.PREFIX_LIST, typeId);
        final DictType dictType = dictTypeService.getById(typeId);
        if (null == dictType) {
            return Collections.emptyList();
        }
        if (dictType.getStatus().equals(Constants.STATUS_DISABLE)) {
            return Collections.emptyList();
        }
        final QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TYPE_ID, typeId);
        queryWrapper.eq("status", Constants.STATUS_ENABLE);
        queryWrapper.orderByAsc("idx");
        final List<DictData> list = redisTemplateUtil.getList(new CacheKey().setKey(key), () -> list(queryWrapper), DictData.class);
        queryWrapper.clear();
        return list;
    }

    @Transactional(readOnly = true)
    public List<DictDataDTO> getListDtoByType(String typeId) {
        final List<DictData> listByType = getListByType(typeId);
        if (listByType.isEmpty()) {
            return Collections.emptyList();
        }
        return listByType.stream().map(this::modelToDto).collect(Collectors.toList());
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getListByTypes(String... types) {
        final Map<String, Object> map = new LinkedHashMap<>(types.length);
        for (String type : types) {
            map.put(type, getListDtoByType(type));
        }
        return map;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<DictData> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<DictData> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(DictData::getId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public String idToDisplay(String id) {
        return Optional.ofNullable(getById(id)).map(DictData::getName).orElse("");
    }
}